﻿using Notifications.Wpf;
using NPinyin;
using SixLabors.ImageSharp.Formats.Jpeg;
using System.Diagnostics;
using System.IO;
using System.Text;
using System.Windows.Media.Imaging;
using VideoTools.Extension;
using VideoTools.vo;
using Image = SixLabors.ImageSharp.Image;

namespace VideoTools.Util
{
    public static class Utils
    {
        public static string GenerateFileNameWithoutExtension(string? fileName)
        {
            string tmpFileName;
            if (string.IsNullOrWhiteSpace(fileName))
                tmpFileName = Guid.NewGuid().ToString("N");
            else
                tmpFileName = EscapeFileName(fileName);
            tmpFileName = fileName;
            return tmpFileName;
        }

        public static string EscapeFileName(string fileName) =>
        Path.GetInvalidFileNameChars().Append('.').Aggregate(fileName, (current, invalidChar) => current.Replace(invalidChar, '_'));
        private static readonly string[] formats = { "ts", "m4s", "mp4" };
        public static bool EnsureFileNotExist(string filename)
        {
            foreach (string item in formats)
            {
                string filePath = filename + '.' + item;
                FileInfo fileInfo = new(filePath);
                if (fileInfo.Exists && fileInfo.Length > 0)
                {
                    return true;
                }
            }
            return false;
        }
        //允许的视频和音频格式
        public static string[] allowFiles()
        {
            List<String> files = new List<string>();
            files.AddRange(AppConstants.__allowVideoFiles);
            files.AddRange(AppConstants.__allowAudioFiles);
            return files.ToArray();
        }

        public static string[] allowAudioFiles()
        {
            return AppConstants.__allowAudioFiles;
        }

        public static string[] allowVideoFiles()
        {
            return AppConstants.__allowVideoFiles;
        }

        public static bool isVideo(string filePath)
        {
            if (filePath == null)
            {
                return false;
            }
            string v = string.Join(";", AppConstants.__allowVideoFiles);
            string[] infos = filePath.Split('.');

            return v.IndexOf(infos[infos.Length - 1].ToLower()) > -1;
        }
        /// <summary>
        /// 获取枚举所有值
        /// </summary>
        /// <returns></returns>
        public static T[] GetAllEnumValues<T>() where T : Enum
        {
            return (T[])Enum.GetValues(typeof(T));
        }

        
        /// <summary>
        /// 读取文件内容
        /// </summary>
        /// <param name="path">读取路径</param>
        /// <returns>返回文件内容</returns>
        public static (string content, List<string> lines) ReadFile(string path)
        {
            if (File.Exists(path))
            {
                try
                {
                    // 创建一个 StreamReader 的实例来读取文件 
                    // using 语句也能关闭 StreamReader
                    using (StreamReader sr = new StreamReader(path))
                    {
                        StringBuilder sbText = new StringBuilder();
                        List<string> lines = new List<string>();
                        // 从文件读取并显示行，直到文件的末尾 
                        while (!sr.EndOfStream)
                        {
                            string line = sr.ReadLine();
                            sbText.AppendLine(line);
                            lines.Add(line);
                        }
                        //Console.WriteLine(sbText.ToString());
                        //Console.WriteLine("count = " + lines.Count);
                        return (sbText.ToString(), lines);
                    }
                }
                catch (Exception err)
                {
                    Console.WriteLine(err.Message);
                    return (null, null);
                }
            }
            else
            {
                return (null, null);
            }
        }
        public static List<GoogleTranslateLanguage> getSortGoogleTranslateLanguages()
        {
            List<GoogleTranslateLanguage> list = new List<GoogleTranslateLanguage>();
            foreach (GoogleTranslateLanguage lang in Enum.GetValues(typeof(GoogleTranslateLanguage)))
            {
                if (lang != GoogleTranslateLanguage.en && lang != GoogleTranslateLanguage.zh)
                {
                    list.Add(lang);
                }

            }

            list.Sort((l1, l2) => {
                string d1 = l1.Desc();
                string d2 = l2.Desc();
                string p1 = Pinyin.GetPinyin(d1);
                string p2 = Pinyin.GetPinyin(d2);
                p1 = p1.Replace(" ", "");
                p2 = p2.Replace(" ", "");
                return Pinyin.GetPinyin(d1).CompareTo(Pinyin.GetPinyin(d2));
            });
            List<GoogleTranslateLanguage> list1 = new List<GoogleTranslateLanguage>();
            list1.Add(GoogleTranslateLanguage.zh);
            list1.Add(GoogleTranslateLanguage.en);
            list1.AddRange(list);
            return list1;
        }
        public static bool isJpegImage(byte[] data)
        {
            try
            {
                var imageInfo = Image.Identify(data);
                return imageInfo != null && imageInfo.Metadata.DecodedImageFormat.Name.Equals("JPEG", StringComparison.OrdinalIgnoreCase);
            }
            catch
            {
                return false;
            }
        }
        public static byte[] AnyImageToJpegImage(byte[] data,int quality = 90)
        {
            if (!Utils.isJpegImage(data))
            {
                // 限制质量范围
                quality = Math.Clamp(quality, 1, 100);

                using (var image = Image.Load(data))
                {
                    var encoder = new JpegEncoder
                    {
                        Quality = quality
                    };

                    using (var memoryStream = new MemoryStream())
                    {
                        image.Save(memoryStream, encoder);
                        return memoryStream.ToArray();
                    }
                }
            }
            return data;
        }

        public static BitmapImage BitmapToBitmapImage(Bitmap bitmap)
        {
            try
            {
                // 将Bitmap转换为WPF的BitmapImage
                BitmapImage bitmapImage;
                using (MemoryStream memory = new MemoryStream())
                {
                    bitmap.Save(memory, System.Drawing.Imaging.ImageFormat.Png);
                    memory.Position = 0;
                    bitmapImage = new BitmapImage();
                    bitmapImage.BeginInit();
                    bitmapImage.StreamSource = memory;
                    bitmapImage.CacheOption = BitmapCacheOption.OnLoad;
                    bitmapImage.EndInit();
                }
                return bitmapImage;
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
            return null;
        }
        public static void OpenUrlUsingEdge(string url)
        {
            string edgePath =
                       @"C:\Program Files (x86)\Microsoft\Edge\Application\msedge.exe";
            if (File.Exists(edgePath))
            {
                Process.Start(
                    new ProcessStartInfo
                    {
                        FileName = edgePath,
                        Arguments = url,
                        UseShellExecute = true,
                    }
                );
            }
            else
            {
                // 回退到默认浏览器
                Process.Start(
                    new ProcessStartInfo { FileName = url, UseShellExecute = true }
                );
            }
        }

        public static void CopyToClipboard(string text,string desc = "")
        {
            if (string.IsNullOrEmpty(text))
            {
                return;
            }
            try
            {
                System.Windows.Clipboard.SetText(text);
            }
            catch (Exception ex)
            {
                var content = new NotificationContent()
                {
                    Title = "有别的应用占用剪贴板,无法复制" + desc,
                    Type = NotificationType.Error,
                    Message = ex.Message
                };
                AppManager.Instance.NotificationManager.Show(content);
            }
        }
    }
}
